package com.forcetools.utils;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;

import org.apache.log4j.Logger;
public class PropertyConfigUtils {
	private static Map<String,Properties> propMasterMap;
	private static Logger logger;
	private static final String PROP_SUFFIX=".properties";
	static{
		propMasterMap = new HashMap<String,Properties>();
		logger = Logger.getLogger(PropertyConfigUtils.class);
	}
	public static String getProperty(String propType,String envName,String propertyName) throws Exception{
		if(propMasterMap.isEmpty()){
			loadProperties();
		}
		String propValue = propMasterMap.get(propType).getProperty(envName+"."+propertyName); 
		if(propValue==null){
			//Try to get a generic property instead of a environment specific configuration
			propValue = propMasterMap.get(propType).getProperty(propertyName);
		}
		return propValue;
	}
	public static String getProperty(String envName,String propertyName) throws Exception{
		if(propMasterMap.isEmpty()){
			loadProperties();
		}
		String propValue = propMasterMap.get(propertyName).getProperty(envName+"."+propertyName); 
		if(propValue==null){
			//Try to get a generic property instead of a environment specific configuration
			propValue = propMasterMap.get(propertyName).getProperty(propertyName);
		}
		return propValue;
	}
	
	
	private static void loadProperties() throws Exception{
		try{
			Properties props = new Properties(),tempProps;
			props.load(PropertyConfigUtils.class.getResourceAsStream("master.properties"));
			String propFileNames = props.getProperty("propertiesToLoad");
			for(String fileName:propFileNames.split(",")){
				tempProps = new Properties();
				tempProps.load(ClassLoader.getSystemResourceAsStream(fileName+PROP_SUFFIX));
				propMasterMap.put(fileName, tempProps);
			}
		}catch(Exception ex){
			logger.error("Could not load sfdc_connection.properties");
			throw ex;
		}
	}
	
	
}
